import pandas as pd
import datetime


def combine_dataset(original_df, pp_df):  # 数据标注 ppxy- mark=1；normal - mark=0
    original_df['mark'] = 0
    pp_df['mark'] = 1
    all_df = pd.concat([original_df, pp_df], ignore_index=True)
    all_df = all_df.sort_values(by=['id', 'time'])
    # duplicates_list = list(all_df.columns)
    # duplicates_list.remove('mark')  # 以上两行code为了去重合并后的df  并保留mark=1的乒乓效应记录数据
    duplicates_list = ['id', 'time', 'x', 'y']
    new_df = all_df.drop_duplicates(subset=duplicates_list, keep='last')
    new_df['time'] = pd.to_datetime(new_df['time'], format="%Y-%m-%d %H:%M:%S", errors='coerce')
    new_df.reset_index(inplace=True, drop=True)
    return new_df


def nearestTime(mark_dataset):  # 最邻近替换
    for i in range(len(mark_dataset)):
        left_time = ''
        right_time = ''
        left_number = 0
        right_number = 0
        # mark_dataset.loc[:, 'time'] = pd.to_datetime(mark_dataset.loc[:, 'time'], format="%Y-%m-%d %H:%M:%S",errors='coerce')
        # mark_dataset['time'] = pd.to_datetime(mark_dataset['time'],format="%Y-%m-%d %H:%M:%S", errors='coerce')
        if mark_dataset.loc[i, 'mark'] == 1:
            pp_time = mark_dataset.loc[i, 'time']
            # 查找临近时间间隔
            for j in range(i - 1, 1, -1):  # pp记录所在前部分数据
                if mark_dataset.loc[j - 1, 'mark'] == 0:
                    left_time = mark_dataset.loc[j, 'time']
                    left_number = j
                    break  # 找到后就中断循环
            for k in range(i + 1, len(mark_dataset)):  # pp记录所在后部分数据
                if mark_dataset.loc[i + 1, 'mark'] == 0:
                    right_time = mark_dataset.loc[k, 'time']
                    right_number = k
                    break
            # 寻找哪个离异常记录最近
            left_time_interval = (pp_time - left_time).seconds
            right_time_interval = (right_time - pp_time).seconds
            # 左侧坐标
            left_x = mark_dataset['x'][left_number]
            print(left_x)
            left_y = mark_dataset['y'][left_number]
            right_x = mark_dataset['x'][right_number]
            right_y = mark_dataset['y'][right_number]
            if left_time_interval <= right_time_interval:
                mark_dataset['x'][i] = left_x
                mark_dataset['y'][i] = left_y
            elif left_time_interval > right_time_interval:
                mark_dataset['x'][i] = right_x
                mark_dataset['y'][i] = right_y
            else:
                print('Have problem?')
            break
    return mark_dataset
